<template>
  <div id="ProcessDetail">
    <el-tabs v-model="tabName" type="border-card">
      <el-tab-pane name="one" label="表单信息">
        <!--    表单    -->
        <header>
          <p class="title">申请信息</p>
          <div class="formBox">
            <VFormRender ref="preForm"
                         :form-json="formJson"
                         :preview-state="true"
                         :form-data="testFormData"
                         v-if="addDialogVisible"
            >
            </VFormRender>
          </div>
        </header>
        <!--    审批任务 -->
        <div v-if="pageType === '流程处理'" class="taskBox">
          <p class="title">审批任务</p>
          <div class="spFromBox">
            <el-form :model="approvalJson" :rules="rules" ref="approvalJson" size="small" label-width="100px">
              <el-form-item label="审批建议" prop="advice">
                <el-input type="textarea" v-model="approvalJson.advice"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="clickHandleBtn">处理</el-button>
                <el-button v-show="isShowZbBtn" type="warning" @click="clickZbBtn">转办</el-button>
                <el-button v-show="isShowCyBtn" type="success" @click="clickCyBtn">传阅</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="two" label="流程信息">
        <main>
          <p class="title">审批记录：</p>
          <div v-if="approveRecords.length">
            <div class="record-container" v-for="(item, index) in approveRecords" :key="index">
              <div v-if="item.endTime">
                <h4>任务：{{ item.name }}</h4>
                <div class="record-box">
                  <div class="record-item">
                    <span>审批人：</span>
                    <span>{{ item.assigneeUser.nickname }}</span>
                  </div>
                  <div class="record-item">
                    <span>创建时间：</span>
                    <span>{{ item.createTime }}</span>
                  </div>
                  <div class="record-item">
                    <span>结束时间：</span>
                    <span>{{ item.endTime }}</span>
                  </div>
                  <div class="record-item">
                    <span>审批意见：</span>
                    <span>{{ item.reason }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <span v-if="approveRecords.length === 0 || (approveRecords.length === 1 && !approveRecords[0].endTime)"
                class="tips">暂无记录</span>
        </main>
        <p class="title">流程图</p>
        <div>
          <ProcessViewer
            :processInstanceData="processInstance"
            key="designer"
            v-model="bpmnXML" v-bind="bpmnControlForm" :activityData="activityList"
            :taskData="tasks"/>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="dealDialogTitle" :visible.sync="dialogVisible" :append-to-body="true" width="30%">
      <div style="display: flex;align-items: center;padding:25px 15px">
        <el-form :model="chiosePerson" :rules="personRules" ref="chiosePerson" size="small" label-width="100px">
          <el-form-item label="选择人员" prop="personVal">
            <el-select ref="userSelect" v-model="chiosePerson.personVal" filterable>
              <el-option
                v-for="(option, index) in peroptions"
                :value="option.value"
                :key="option.value + index"
                :label="option.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmeZbCy">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VFormRender from '@/views/lowcode/components/form-render/index'
import ProcessViewer from '@/views/workflow/approval/ProcessViewer'

export default {
  name: 'ProcessDetail',
  components: {
    VFormRender,
    ProcessViewer
  },
  props: {
    detaileQueryParam: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      approvalJson: {
        advice: ''
      },
      tasks: [],
      bpmnXML: '',
      formJson: {},
      addDialogVisible: false,
      testFormData: {},
      formId: '',
      processInstanceId: '',
      processDefinitionId: '',
      taskDefinitionKey: '',
      isDisableFields: [],
      pageType: '',
      activityList: [],
      taskId: '',
      approveRecords: [],
      dialogVisible: false,
      chiosePerson: {
        personVal: ''
      },
      peroptions: [
        { label: '张三', value: '1' }
      ],
      dealDialogTitle: '转办',
      processName: '',
      createTime: '',
      bpmnControlForm: {
        prefix: 'activiti'
      },
      rules: {
        advice: [
          { required: true, message: '请输入审批建议', trigger: 'blur' }
        ]
      },
      personRules: {
        personVal: [
          { required: true, message: '请选择人员', trigger: 'blur' }
        ]
      },
      tabName: 'two',
      processDefinitionKey: '',
      isShowZbBtn: true,
      isShowCyBtn: true,
      processInstance: {}
    }
  },
  watch: {
    $route: {
      handler (to, from) {
        from.path === '/person' ? this.initPage() : ''
      }
    }
  },
  methods: {
    // 初始化
    initPage () {
      this.formId = this.detaileQueryParam.formId
      this.processInstanceId = this.detaileQueryParam.processInstanceId
      this.processDefinitionId = this.detaileQueryParam.processDefinitionId
      this.taskDefinitionKey = this.detaileQueryParam.taskCode
      this.pageType = this.detaileQueryParam.type
      this.taskId = this.detaileQueryParam.id
      this.processName = this.detaileQueryParam.processName
      this.createTime = this.detaileQueryParam.createTime
      this.processDefinitionKey = this.detaileQueryParam.processDefinitionKey
      // 流程图
      this.getProcessChart()
      // 拿到总审批记录
      this.getRecordList()
      // 高亮
      this.highLightBpmn()
      // 默认值
      this.getFormDefaultData()
      // 人员
      this.pageType === '流程处理' ? this.getUserList() : ''
      // 按钮权限控制
      this.pageType === '流程处理' ? this.controlBtn() : ''
      //
      this.getLastData()
    },
    getLastData () {
      this.$http.get('/api/flow/process/get', {
        params: { id: this.processInstanceId }
      }).then(res => {
        this.processInstance = res.data.result
      })
    },
    controlBtn () {
      this.$http.get('/api/flow/rule/taskPerm-select', {
        params: {
          taskDefinitionKey: this.taskDefinitionKey,
          taskDefinitionFlag: this.processDefinitionKey
        }
      }).then(res => {
        let perm = res.data?.result[0] ? res.data.result[0].perms : ''
        if (!perm) {
          this.isShowZbBtn = false
          this.isShowCyBtn = false
        } else if (perm === '10,11') {
          this.isShowZbBtn = true
          this.isShowCyBtn = true
        } else if (perm === '10') {
          this.isShowZbBtn = false
          this.isShowCyBtn = true
        } else if (perm === '11') {
          this.isShowZbBtn = true
          this.isShowCyBtn = false
        }
      })
    },
    // 流程图
    getProcessChart () {
      this.$http.get('/api/flow/def/get-bpmn-xml', { params: { id: this.processDefinitionId } }).then(res => {
        this.bpmnXML = res.data.result
      })
    },
    // 按钮操作
    clickHandleBtn () {
      this.$refs.approvalJson.validate((valid) => {
        if (valid) {
          let params = {
            flowMap: this.testFormData,
            id: this.taskId,
            reason: this.approvalJson.advice
          }
          this.$http.put('/api/flow/core/approve', params).then(res => {
            this.$Message.success('处理成功！')
            this.$emit('reloadPage')
          }).catch(err => {
            this.$Message.error('服务器错误！')
          })
        }
      })
    },
    // 人员
    getUserList () {
      this.$http.get('api/system/cscpUserDetailsOr').then(response => {
        const op = []
        for (let item of response.data.data) {
          op.push({
            value: item.userId,
            label: `${item.username} `
          })
        }
        this.peroptions = op
      }).catch()
    },
    clickZbBtn () {
      this.dialogVisible = true
      this.dealDialogTitle = '转办'
      this.chiosePerson.personVal = ''
    },
    clickCyBtn () {
      this.dialogVisible = true
      this.dealDialogTitle = '传阅'
      this.chiosePerson.personVal = ''
    },
    getFormData () {
      this.$refs['preForm'].getFormData().then(res => {

      })
    },
    // 转办或传阅
    confirmeZbCy () {
      this.$refs.chiosePerson.validate((valid) => {
        if (valid) {
          this.dealDialogTitle === '转办' ? this.zbNetApi() : this.cyNetApi()
        }
      })
    },
    zbNetApi () {
      let params = {
        assigneeUserId: this.chiosePerson.personVal,
        id: this.taskId
      }
      this.$http.put('/api/flow/core/update-assignee', params).then(res => {
        this.$Message.success('转办成功！')
        this.dialogVisible = false
        this.$emit('reloadPage')
      }).catch(err => {
        this.$Message.error('转办失败！')
      })
    },
    cyNetApi () {
      let params = {
        userId: this.chiosePerson.personVal,
        formId: this.formId,
        processId: this.processDefinitionId,
        processInstid: this.processInstanceId,
        processName: this.processName,
        type: 1,
        createTime: this.createTime
      }
      this.$http.post('/api/flow/door/rdTurnTask-create', params).then(res => {
        this.$Message.success('传阅成功！')
        this.dialogVisible = false
        this.$emit('reloadPage')
      }).catch(err => {
        this.$Message.error('传阅失败！')
      })
    },
    // 按钮控制

    // 获取formJson
    getFormJson () {
      this.addDialogVisible = false
      this.$http.get('/api/lowcode/customize/cscpCustomizeVforms/' + this.formId).then(res => {
        if (this.pageType === '流程处理') {
          // 权限控制
          this.accessControl().then(innerres => {
            this.isDisableFields = []
            innerres.data.data.map(item => {
              if (item.perm === '0') { // 可以编辑
                this.isDisableFields.push(item.fieldId)
              }
            })
            // 处理formJson
            this.formJson = JSON.parse(res.data.formJson)
            this.formJson.widgetList.map(item => {
              if (this.isDisableFields.indexOf(item.options.name) !== -1) { // 可编辑
                item.options.disabled = false
              } else {
                item.options.disabled = true
              }
            })
            this.addDialogVisible = true
          })
        } else if (this.pageType === '流程详情') {
          // 处理formJson
          this.formJson = JSON.parse(res.data.formJson)
          this.formJson.widgetList.map(item => {
            item.options.disabled = true
          })
          this.addDialogVisible = true
        }
      })
    },
    // 拿到总审批记录
    getRecordList () {
      this.approveRecords = []
      let params = {
        processInstanceId: this.processInstanceId
      }
      this.$http.get('/api/flow/core/list-by-process-instance-id', { params }).then(res => {
        this.approveRecords = res.data.result
        let response = res.data.result
        // 审批记录
        this.tasks = []
        // 移除已取消的审批
        response.forEach(task => {
          if (task.result !== 4) {
            this.tasks.push(task)
          }
        })
        // 排序，将未完成的排在前面，已完成的排在后面；
        this.tasks.sort((a, b) => {
          // 有已完成的情况，按照完成时间倒序
          if (a.endTime && b.endTime) {
            return b.endTime - a.endTime
          } else if (a.endTime) {
            return 1
          } else if (b.endTime) {
            return -1
            // 都是未完成，按照创建时间倒序
          } else {
            return b.createTime - a.createTime
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 表单权限
    accessControl () {
      return this.$http.get('/api/lowcode/customize/qryTableFieldPerm', {
        params: {
          taskDefinitionKey: this.taskDefinitionKey,
          taskDefinitionFlag: this.processDefinitionKey
        }
      })

    },
    // 流程图高亮
    highLightBpmn () {
      this.$http.get('/api/flow/process/list', { params: { processInstanceId: this.processInstanceId } }).then(res => {
        this.activityList = res.data.result
      })
    },
    // 表单默认值
    getFormDefaultData () {
      let params = {
        instance_id: this.processInstanceId
      }
      this.$http.get('/api/lowcode/customize/template/queryByInstanceId/' + this.formId, { params }).then(res => {
        this.testFormData = res.data.data
        // 拿到formJson
        this.getFormJson()
      })
    }
  },
  mounted () {
    this.initPage()
  }
}
</script>

<style lang="less">
#ProcessDetail {
  width: 100%;
  height: 100%;
  background-color: #fff;

  .el-tabs {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-tabs__header {
      height: 49px;
      padding: 0;
    }

    .el-tabs__content {
      flex: 1;
      overflow: auto;

      .el-tab-pane {
        height: 100%;
        display: flex;
        flex-direction: column;

        header {
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          margin-bottom: 25px;
          display: flex;
          flex-direction: column;
          align-items: center;

          .formBox {
            width: 60%;
            padding: 15px;
            max-height: 350px;
            overflow-y: auto;
          }

          .formBox::-webkit-scrollbar {
            display: none;
          }
        }

        .taskBox {
          height: 200px;
          margin-bottom: 25px;
          width: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          flex: 1;
          flex-shrink: 0;

          .spFromBox {
            width: 60%;
            padding: 15px;

            .el-form {
              .el-form-item:last-child {
                .el-form-item__content {
                  display: flex;
                  justify-content: center;
                  align-items: center;
                }
              }
            }
          }
        }

        main {
          width: 100%;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          flex: 1;
          margin-bottom: 25px;
          display: flex;
          flex-direction: column;
          align-items: center;
          flex-shrink: 0;

          .record-container {
            width: 80%;
            flex: 1;
            max-height: 350px;
            overflow-y: auto;

            .record-box {
              box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
              padding: 15px;
              margin-top: 15px;
              display: flex;

              .record-item {
                margin: 0 15px;
              }
            }
          }
        }

        footer {
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          flex: 2;
          flex-shrink: 0;
          min-height: 300px;
        }
      }
    }
  }

  .title {
    padding: 15px;
    border-bottom: 1px solid rgba(0, 0, 0, .12);
    margin-bottom: 15px;
    width: 100%;
  }
}
</style>
